package com.example.web.controller;

import com.example.web.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * Create by keboom on 2020/7/4
 */
@Controller
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @GetMapping("/mall/login")
    public String loginGet(){
        return "login";
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param model
     * @param session
     * @return
     */
    @PostMapping("/mall/login")
    public String login(String username, String password,
                        Model model, HttpSession session) {
        String forPassword = userMapper.selectByNameForPassword(username);
        if (forPassword == null) {
            model.addAttribute("msg", "没有此用户，请先注册！");
            return "register";
        }else if (!forPassword.equals(password)) {
            model.addAttribute("msg", "用户名存在但密码错误！");
            return "login";
        }else {
            if (session.getAttribute("username")!=null && !username.equals(session.getAttribute("username"))){
                model.addAttribute("msg","同一个客户端不可以登录两个用户！");
                return "login";
            }
            session.setAttribute("username", username);
            return "redirect:shop";
        }

    }

}
